using System;
using System.Web.Mvc;
using Toast.ContentTypes;
using Toast.Core;
using Toast.Extensions;

namespace Toast
{
    public class ToastViewEngineWrapper : WebFormViewEngine
    {
        static WebFormViewEngine _viewEngine;

        ToastViewEngineWrapper(WebFormViewEngine viewEngine)
        {
            _viewEngine = viewEngine;
        }

        public static WebFormViewEngine Wrap(WebFormViewEngine viewEngine)
        {
            return new ToastViewEngineWrapper(viewEngine);
        }

        public static WebFormViewEngine Wrap<TViewEngine>() where TViewEngine : WebFormViewEngine
        {
            return new ToastViewEngineWrapper(Activator.CreateInstance<TViewEngine>());
        }

        protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)
        {
            if (controllerContext.HttpContext.Request.IsAjaxRequest())
                RegisterAjaxViewRequest(partialPath);
            else
                RegisterViewRequest(partialPath);

            return base.CreatePartialView(controllerContext, partialPath);
        }

        protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
        {
            if (controllerContext.HttpContext.Request.IsAjaxRequest())
                RegisterAjaxViewRequest(viewPath);
            else
                RegisterViewRequest(viewPath);

            return base.CreateView(controllerContext, viewPath, masterPath);
        }

        static void RegisterViewRequest(string path)    
        {
            if (!path.IsNullOrEmpty())
                RequestContentTable.Contents.Add(LocalJavaScriptFile.FromPath(path + ".js"));
        }

        static void RegisterAjaxViewRequest(string path)
        {
            if (!path.IsNullOrEmpty()) 
                RequestContentTable.Contents.Add(EmbededJavaScriptContent.FromFile(path + ".js", InjectAt.Inline));
        }
    }
}